﻿using Microsoft.Extensions.Logging;

namespace Infrastructure.Persistence;

public class ApplicationDbContextInitializer : IScopedDependency
{
    private readonly ILogger<ApplicationDbContextInitializer> _logger;
    private readonly ApplicationDbContext _context;

    public ApplicationDbContextInitializer(
    ILogger<ApplicationDbContextInitializer> logger,
    ApplicationDbContext context)
    {
        _logger = logger;
        _context = context; 
    }

    /// <summary>
    /// 如果不存在则创建数据库
    /// </summary>
    /// <returns></returns>
    public async Task CreateIfNotExistsDatabaseAsync()
    {
        try
        {
            if (_context.Database.IsSqlServer() ||
                _context.Database.IsNpgsql() ||
                _context.Database.IsSqlite() ||
                _context.Database.IsMySql())
            {
                if (await IsDatabaseExistsAsync())
                {
                    _logger.LogDebug("数据库已经存在，自动退出创建数据库");
                    return;
                }
                _logger.LogDebug("数据库不存在，自动创建数据库中......");
                await _context.Database.MigrateAsync();
                _logger.LogDebug("数据库已建好");
            }
        }
        catch (Exception ex)
        {
            _logger.LogDebug($"自动创建数据库时出错:{ex.Message}");
            throw;
        }
    }

    public async Task<bool> IsDatabaseExistsAsync()
    {
        try
        {
            return await _context.Database.CanConnectAsync();
        }
        catch (Exception ex)
        {
            // 处理连接异常
            _logger.LogDebug($"连接数据库时出现异常: {ex.Message}");
            return false;
        }
    }
}
